package org.zjx.common.db;

import org.zjx.common.bean.Screen;
import org.zjx.common.util.db.SQLiteHelper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ScreenDB {
    private static boolean isTableCreated = false;
    private final SQLiteHelper dbHelper;

    public ScreenDB() {
        dbHelper = SQLiteHelper.getSingleton();
        if (!isTableCreated) {
            createTable();
            isTableCreated = true;
        }
    }

    // 修改后的建表语句
    public void createTable() {
        String createTable = "CREATE TABLE IF NOT EXISTS screen (\n"
                + "    id INTEGER PRIMARY KEY AUTOINCREMENT,\n"
                + "    name TEXT NOT NULL,\n"
                + "    fatherId INTEGER,\n"        // 新增字段
                + "    openMap INTEGER,\n"         // Boolean转INTEGER存储
                + "    width INTEGER,\n"           // 类型修正
                + "    height INTEGER,\n"          // 类型修正
                + "    follow INTEGER\n"           // boolean转INTEGER存储
                + ");";
        dbHelper.createTable(createTable);
    }

    // 修改后的插入方法
    public void insert(Screen screen) {
        String sql = "INSERT INTO screen(name, fatherId, openMap, width, height, follow) VALUES(?, ?, ?, ?, ?, ?)";
        Object[] params = {
                screen.getName(),
                screen.getFatherId(),
                screen.getOpenMap() ? 1 : 0,  // Boolean转INTEGER
                screen.getWidth(),
                screen.getHeight(),
                screen.isFollow() ? 1 : 0    // boolean转INTEGER
        };
        dbHelper.executeUpdate(sql, params);
    }

    // 修改后的更新方法
    public void update(Screen screen) {
        String sql = "UPDATE screen SET name=?, fatherId=?, openMap=?, width=?, height=?, follow=? WHERE id=?";
        Object[] params = {
                screen.getName(),
                screen.getFatherId(),
                screen.getOpenMap() ? 1 : 0,
                screen.getWidth(),
                screen.getHeight(),
                screen.isFollow() ? 1 : 0,
                screen.getId()
        };
        dbHelper.executeUpdate(sql, params);
    }

    // 以下方法保持结构不变，但查询结果会自动映射新字段
    // （假设SQLiteHelper已支持新字段的映射）

    public void deleteById(int id) {
        String sql = "DELETE FROM screen WHERE id = ?";
        Object[] params = {id};
        dbHelper.executeUpdate(sql, params);
    }

    public Screen findById(int id) {
        String sql = "SELECT * FROM screen WHERE id = ?";
        Object[] params = {id};
        List<Screen> screens = dbHelper.executeQuery(sql, params, Screen.class);
        return screens.isEmpty() ? null : screens.get(0);
    }

    public Screen findByName(String name) {
        String sql = "SELECT * FROM screen WHERE name = ?";
        Object[] params = {name};
        List<Screen> screens = dbHelper.executeQuery(sql, params, Screen.class);
        return screens.isEmpty() ? null : screens.get(0);
    }

    public List<Screen> findAll() {
        String sql = "SELECT * FROM screen";
        return dbHelper.executeQuery(sql, new Object[]{}, Screen.class);
    }

    public Map<String, Object> findAllWithPagination(int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        String sql = "SELECT * FROM screen LIMIT ? OFFSET ?";
        List<Screen> screens = dbHelper.executeQuery(sql, new Object[]{pageSize, offset}, Screen.class);

        String countSql = "SELECT COUNT(*) FROM screen";
        int totalRecords = dbHelper.executeQuery(countSql, new Object[]{}, Integer.class)
                .stream().findFirst().orElse(0);

        int totalPages = (int) Math.ceil((double) totalRecords / pageSize);


        Map<String, Object> result = new HashMap<>();
        result.put("screenList", screens);
        result.put("totalRecords", totalRecords);
        result.put("totalPages", totalPages);
        result.put("currentPage", pageNum);

        return result;
    }

    public void clearData() {
        dbHelper.clearData("screen");
    }

    public void dropTable() {
        dbHelper.dropTable("screen");
    }
}
